import { BaseCardExtractor } from './base-card-extractor.js';
import { selectors } from '../config.js';

/**
 * 通用表格数据提取器
 * 支持配置表格选择器、行标题索引、是否忽略最后一列
 */
export class TableCardExtractor extends BaseCardExtractor {
  constructor(options = {}) {
    super({
      card: options.tableSelector || selectors.table || '.byted-Table',
      name: selectors.tableHeadCell,
      value: selectors.tableCell
    });
    this.tableSelector = options.tableSelector || '.byted-Table';
  }

  // 返回表格容器选择器
  getCardSelector() {
    return this.tableSelector;
  }

  // 以表格容器为参数，返回一维卡片数组
  extract(table) {
    const result = [];
    if (!table) return result;

    // 添加表格标题标签
    const tableTitle = table.querySelector('.byted-Table-Header')?.textContent.trim() || '表格数据';
    const label = document.createElement('div');
    label.textContent = tableTitle;
    label.className = 'auto-table-label';
    label.style.cssText = `
      position: absolute;
      top: -25px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 16px;
      font-weight: bold;
      color: #0066cc;
      background: #f5f5f5;
      border: 2px solid #0066cc;
      border-radius: 0;
      padding: 2px 6px;
      z-index: 9999;
      pointer-events: none;
    `;
    table.style.position = 'relative';
    table.appendChild(label);

    // 获取列头
    const headerEls = Array.from(table.querySelectorAll('.byted-Table-HeadCellContentTitle'));
    const columnHeaders = headerEls.map(el => el.innerText.trim());
    const colCount = columnHeaders.length;

    // 获取所有行
    const rows = Array.from(table.querySelectorAll('.byted-Table-Body .byted-Table-Row'));
    const rowspanMap = {}; // 跨行缓存
    let lastGroupLabel = ''; // 用于存储合并行的主分类
    const labelCount = {}; // 用于记录label出现次数

    rows.forEach((row, rowIndex) => {
      // 添加行样式
      row.style.backgroundColor = `hsla(210, 70%, ${80 - (rowIndex % 3) * 10}%, 0.3)`;
      row.style.border = '1px solid #0066cc';
      row.style.borderRadius = '6px';
      row.style.margin = '2px 0';

      const physicalCells = Array.from(row.querySelectorAll('.byted-Table-Cell'));
      const logicalCells = [];
      let realColIndex = 0;

      // 还原逻辑列结构（补齐rowspan）
      while (realColIndex < colCount) {
        if (rowspanMap[realColIndex]?.remaining > 0) {
          logicalCells.push(rowspanMap[realColIndex].cell);
          rowspanMap[realColIndex].remaining -= 1;
          realColIndex++;
        } else if (physicalCells.length > 0) {
          const cell = physicalCells.shift();
          const rowspan = parseInt(cell.getAttribute('rowspan') || '1');
          if (rowspan > 1) {
            rowspanMap[realColIndex] = { cell, remaining: rowspan - 1 };
          }
          logicalCells.push(cell);
          realColIndex++;
        } else {
          logicalCells.push(null);
          realColIndex++;
        }
      }

      // 创建每行数据对象
      const rowData = { type: 'table' };

      for (let i = 0; i < colCount; i++) {
        const cell = logicalCells[i];
        if (!cell) continue;

        const text = cell.querySelector('span[style*="font-weight: 500"]')?.innerText.trim()
                   || cell.innerText?.trim()
                   || '';

        if (i === 0) {
          // 第一列为主类（label）
          const label = text || lastGroupLabel;
          if (text) lastGroupLabel = text;
          
          // 处理重复的label
          if (!labelCount[label]) {
            labelCount[label] = 1;
            rowData.label = label;
          } else {
            labelCount[label]++;
            rowData.label = `${label}${labelCount[label]}`;
          }
        } else {
          const header = columnHeaders[i] || `列${i + 1}`;
          rowData[header] = text;
        }
      }

      result.push(rowData);
    });

    return result;
  }
} 